package com.qys.livesMall.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.product.entity.H2ProductSkuAttribute;
import com.qys.livesMall.product.entity.ProductSkuAttributeOptions;
import com.qys.livesMall.product.mapper.H2ProductSkuAttributeMapper;
import com.qys.livesMall.product.mapper.ProductSkuAttributeOptionsMapper;
import com.qys.livesMall.product.service.H2ProductSkuAttributeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gmx
 * @since 2023-05-17
 */
@Service
public class H2ProductAttributeServiceImpl extends ServiceImpl<H2ProductSkuAttributeMapper, H2ProductSkuAttribute> implements H2ProductSkuAttributeService {
    @Resource
    H2ProductSkuAttributeMapper h2ProductSkuAttributeMapper;
    @Resource
    ProductSkuAttributeOptionsMapper optionsMapper;
    /***
     * 根据分类ID查询属性集合
     * @param id
     * @return
     */
    @Override
    public List<H2ProductSkuAttribute> queryList(Long id) {
        return h2ProductSkuAttributeMapper.queryByCategoryId(id);
    }

    @Override
    public String getSkuName(String attr) {
        StringBuilder skuNameBuilder = new StringBuilder();
        Map<String,String> attrMap = JSON.parseObject(attr,
                Map.class);
        for (Map.Entry<String, String> entry : attrMap.entrySet()) {
            String attrName = this.getById(entry.getKey()).getName();
            ProductSkuAttributeOptions attrOption = optionsMapper.selectById(entry.getValue());
            String skuName = attrName + ":" + attrOption.getName();
            skuNameBuilder.append(skuName).append("-");
        }
        if (skuNameBuilder.length() > 0) {
            skuNameBuilder.deleteCharAt(skuNameBuilder.length() - 1);
        }

        String finalSkuName = skuNameBuilder.toString();
        return finalSkuName;
    }

    @Override
    public List<H2ProductSkuAttribute>  getBySpuId(Long spuId){
        LambdaQueryWrapper<H2ProductSkuAttribute> qw=new LambdaQueryWrapper<>();
        qw.eq(H2ProductSkuAttribute::getSpuId,spuId);
        return list(qw);
     }
}
